import _ from 'lodash'
import Promise from 'promise'

export default {
  validateWrapper: function (ruleParams, defaultRuleParams, value, config, model, formModel, validateFunction) {
    let params = ruleParams
    let errorMessage = null
    if (_.isNil(params)) {
      params = defaultRuleParams
    } else {
      if (_.isObject(params) && params.validator && params.validator instanceof Function && params.errorMessage !== undefined) {
        errorMessage = params.errorMessage
        params = params.validator
      }
    }
    if (!_.isNil(params)) {
      if (params instanceof Function) {
        let rst = params(value, config, model, formModel)
        if (rst.then && rst.then instanceof Function) {
          return {
            result: rst.then(data => {
              return Promise.resolve(validateFunction(data, value, model, formModel))
            }),
            errorMessage
          }
        } else {
          params = rst
        }
      }
      return {result: validateFunction(params, value, model, formModel), errorMessage}
    }
    // no rule params, return true
    return {result: true}
  }
}
